<?php
	include_once "db/db.php";
	
	if (isset($_POST['name'])) {
		// Get random life cards
		$life_card_count = mysql_result(mysql_query("SELECT SUM(`lifecards`) FROM `retirementhome"), 0);
		$life_card_query = mysql_query("
			SELECT `id` FROM `lifecard` ORDER BY RAND() LIMIT $life_card_count");
		$life_card_ids = array();
		while ($life_card = mysql_fetch_assoc($life_card_query)) {
			array_push($life_card_ids, $life_card['id']);
		}
		$life_card_string = "|" . implode("|", $life_card_ids) . "|";
		
		// Create game
		$datetime = current_date_time();
		mysql_query("
			INSERT INTO `game` (`name`, `started`, `lastopened`, `millionairelifecards`) 
			VALUES ('" . $_POST['name'] . "', '$datetime', '$datetime', '$life_card_string')");
		$_SESSION['game'] = mysql_result(mysql_query("SELECT `id` FROM `game` WHERE `started` = '$datetime'"), 0);
		header("location:config.php");
	}
	
	$hide_nav = true;
	include_once "header.php";
?>

<script type="text/javascript">
	jQuery(document).ready(function () {
		jQuery("#gameName").focus();
		jQuery("#btnCancel").click(function () {
			window.location = "index.php";
		});
	});
</script>

<h2>Create a new Game</h2>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
<table>
	<tr>
		<th>Game name</th>
		<td><input name="name" id="gameName"/></td>
	</tr>
	<tr>
		<td colspan="2" class="actions">
			<input type="submit" value="Create Game"/>
			<input type="reset" value="Cancel" id="btnCancel"/>
		</td>
	</tr>
</table>
</form>

<?php
	include_once "footer.php";
?>
